package com.drk.farmseason;

import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.BoundCamera;
import org.anddev.andengine.engine.camera.hud.HUD;
import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl;
import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener;
import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl;
import org.anddev.andengine.engine.handler.physics.PhysicsHandler;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXLayer;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXLoader;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXLoader.ITMXTilePropertiesListener;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXProperties;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTile;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTileProperty;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTiledMap;
import org.anddev.andengine.entity.layer.tiled.tmx.util.exception.TMXLoadException;
import org.anddev.andengine.entity.modifier.ScaleModifier;
import org.anddev.andengine.entity.modifier.SequenceEntityModifier;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.ChangeableText;
import org.anddev.andengine.entity.util.FPSCounter;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.ui.activity.BaseGameActivity;
import org.anddev.andengine.util.Debug;

import android.graphics.Color;
import android.graphics.Typeface;
import android.widget.Toast;

public class FarmSeasonActivity extends BaseGameActivity implements IOnSceneTouchListener {
	private static final int CAMERA_WIDTH = 480;
	private static final int CAMERA_HEIGHT = 320;
	//private static final String TAG = "FarmSeason";
	
	// ===========================================================
	// Fields
	// ===========================================================
	// HUD/FPS
	private Texture mFontTexture;
	private Font mFont;
	//Player texture
	private TiledTextureRegion mPlayerTextureRegion;
	private Texture mPlayerTexture;
	// Onscreen controls
	private Texture mOnScreenControlTexture;
	private TextureRegion mOnScreenControlBaseTextureRegion;
	private TextureRegion mOnScreenControlKnobTextureRegion;
	AnimatedSprite player;
	
	private BoundCamera mCamera;
	private Texture mPlantTexture;
	private TextureRegion mPlantTextureRegion;
	public int mCactusCount = 0;
	//private Texture mTexture;
	//private TiledTextureRegion mPlayerTextureRegion;
	private TMXTiledMap mTMXTiledMap;
	
	
	// Objects
	private Texture mCarrotTexture;
	private TiledTextureRegion mCarrotTexttureRegion;
	
	Plants myplants = new Plants();
	
	@Override
	public Engine onLoadEngine() {
		this.mCamera = new BoundCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
	}

	@Override
	public void onLoadResources() {
		//Carrot
		this.mCarrotTexture = new Texture(256,256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mCarrotTexttureRegion = TextureRegionFactory.createTiledFromAsset(this.mCarrotTexture, this, "gfx/onions.png", 0, 0, 6, 1); // 48x16
		
		this.mPlantTexture = new Texture(32,32, TextureOptions.DEFAULT);
		this.mPlantTextureRegion = TextureRegionFactory.createFromAsset(this.mPlantTexture,this,"gfx/carrot.png",0,0);
		
		this.mPlayerTexture = new Texture(128,128, TextureOptions.DEFAULT);
		this.mPlayerTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mPlayerTexture, this, "gfx/player.png", 0, 0, 3, 4); // 72x128

		//this.mTexture = new Texture(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		//this.mFaceTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture, this, "gfx/grass.png", 0, 0);
		this.mOnScreenControlTexture = new Texture(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mOnScreenControlBaseTextureRegion = TextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "gfx/onscreen_control_base.png", 0, 0);
		this.mOnScreenControlKnobTextureRegion = TextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "gfx/onscreen_control_knob.png", 128, 0);

		this.mEngine.getTextureManager().loadTextures(this.mPlayerTexture, this.mOnScreenControlTexture,this.mCarrotTexture,this.mPlantTexture);
		
		this.mFontTexture = new Texture(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);

		this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 48, true, Color.BLACK);

		this.mEngine.getTextureManager().loadTexture(this.mFontTexture);
		this.mEngine.getFontManager().loadFont(this.mFont);
	}

	@Override
		public Scene onLoadScene() {
			final FPSCounter fpsCounter = new FPSCounter();
			this.mEngine.registerUpdateHandler(fpsCounter);
		
		final Scene scene = new Scene(2);

		try {
			final TMXLoader tmxLoader = new TMXLoader(this, this.mEngine.getTextureManager(), TextureOptions.BILINEAR_PREMULTIPLYALPHA, new ITMXTilePropertiesListener() {
				
				@Override
				public void onTMXTileWithPropertiesCreated(final TMXTiledMap pTMXTiledMap, final TMXLayer pTMXLayer, final TMXTile pTMXTile, final TMXProperties<TMXTileProperty> pTMXTileProperties) {
					/* We are going to count the tiles that have the property "cactus=true" set. */
					if(pTMXTileProperties.containsTMXProperty("1", "true")) {
						FarmSeasonActivity.this.mCactusCount++;
					}
				}
			});
			this.mTMXTiledMap = tmxLoader.loadFromAsset(this, "home.tmx");

			Toast.makeText(this, "Cactus count in this TMXTiledMap: " + this.mCactusCount, Toast.LENGTH_LONG).show();
		} catch (final TMXLoadException tmxle) {
			Debug.e(tmxle);
		}

		final TMXLayer tmxLayer = this.mTMXTiledMap.getTMXLayers().get(0);
		scene.getFirstChild().attachChild(tmxLayer);

		/* Make the camera not exceed the bounds of the TMXEntity. */
		this.mCamera.setBounds(0, tmxLayer.getWidth(), 0, tmxLayer.getHeight());
		this.mCamera.setBoundsEnabled(true);

		
		final ChangeableText fpsText = new ChangeableText(10, 10, this.mFont, "FPS:", "FPS: XXXXX".length());
		HUD myhud = new HUD();
		myhud.getLastChild().attachChild(fpsText);
		mCamera.setHUD(myhud);
		//scene.getLastChild().attachChild(fpsText);
		scene.registerUpdateHandler(new TimerHandler(2.0f, true, new ITimerCallback() {
			@Override
			public void onTimePassed(final TimerHandler pTimerHandler) {
				//elapsedText.setText("Seconds elapsed: " + ChangeableTextExample.this.mEngine.getSecondsElapsedTotal());
				fpsText.setText("FPS: " + fpsCounter.getFPS());
			}
		}));
		/* Calculate the coordinates for the face, so its centered on the camera. */
		final int centerX = (CAMERA_WIDTH - this.mPlayerTextureRegion.getTileWidth()) / 2;
		final int centerY = (CAMERA_HEIGHT - this.mPlayerTextureRegion.getTileHeight()) / 2;

		/* Create the sprite and add it to the scene. */
		player = new AnimatedSprite(centerX, centerY, this.mPlayerTextureRegion);
		
		this.mCamera.setChaseEntity(player);
		final Sprite me = new Sprite(288,288,this.mPlantTextureRegion);
		scene.getLastChild().attachChild(me);

		// On screen controls
		final PhysicsHandler physicsHandler = new PhysicsHandler(player);
		player.registerUpdateHandler(physicsHandler);
		scene.getLastChild().attachChild(player);
		final AnalogOnScreenControl analogOnScreenControl = new AnalogOnScreenControl(0, CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(), this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, 200, new IAnalogOnScreenControlListener() {
			
			@Override
			public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) {
				physicsHandler.setVelocity(pValueX * 100, pValueY * 100);
				player.animate(new long[]{200, 200, 200}, 6, 8, true);
			}

			@Override
			public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) {
				player.registerEntityModifier(new SequenceEntityModifier(new ScaleModifier(0.25f, 1, 1.5f), new ScaleModifier(0.25f, 1.5f, 1)));
			}
		});
		analogOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		analogOnScreenControl.getControlBase().setAlpha(0.5f);
		analogOnScreenControl.getControlBase().setScaleCenter(0, 128);
		analogOnScreenControl.getControlBase().setScale(1.25f);
		analogOnScreenControl.getControlKnob().setScale(1.25f);
		analogOnScreenControl.refreshControlKnobPosition();

		scene.setChildScene(analogOnScreenControl);
		scene.setOnSceneTouchListener(this);
		return scene;
	}
	@Override
   public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
                final TMXTile targetTile = this.mTMXTiledMap.getTMXLayers().get(0).getTMXTileAt(pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
                //Toast.makeText(this, "click at " + targetTile.getTileX() + "-" + targetTile.getTileY(), Toast.LENGTH_SHORT).show();
                
                if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP) {
                     if(targetTile.getGlobalTileID() == 2) {
                    	 PlantaPlant(targetTile);
                     }
                	 //this.player.setPosition(targetTile.getTileX(), targetTile.getTileY());
                }
                return true;
    }
	@Override
	public void onLoadComplete() {
		// TODO Auto-generated method stub
		
	}
	
	public void PlantaPlant(TMXTile target) {
		customsprite myplant = new customsprite(target.getTileX(),target.getTileY(),this.mCarrotTexttureRegion.clone(),this);
     //Sprite myplant = new Sprite(target.getTileX(),target.getTileY(),this.mPlantTextureRegion);
		this.mEngine.getScene().registerTouchArea(myplant);
		this.mEngine.getScene().getLastChild().attachChild(myplant);
		Toast.makeText(this, "Planting at " + target.getTileX() + "-" + target.getTileY(), Toast.LENGTH_LONG).show();
		
	}
	
	
}